<!-- 包租合同详情 -->
<template>
	<a-modal
		v-bind="options"
		width="90vw"
		wrap-class-name="a-modal-tab-dialog"
		:footer="isShowFooter"
		:body-style="{
			height: '80vh',
			overflow: 'auto',
			padding: '12px'
		}">
		<template #title>
			<div class="a-modal-tab-title" style="height: 56px">
				<a-card
					class="dialog-card-container"
					:tab-list="detailTabs.map((item: any) => ({key: item.key, tab: item.value}))"
					:active-tab-key="activeKey"
					@tabChange="(key: any) => (activeKey = key)" />
			</div>
		</template>
		<a-row style="height: 100%">
			<!-- ['合约信息', '房间信息', '房间合同', '入住信息', '账单信息'] -->
			<a-col
				:span="
					props.contract?.isApproval && ['singleRentOut', 'contract', 'room', 'single', 'checkIn', 'bill'].includes(activeKey)
						? 17
						: 24
				"
				:class="{'contract-information-left': props.contract?.isApproval}">
				<!-- 单方退租 -->
				<single-room-rent-out-details
					v-if="activeKey == 'singleRentOut'"
					:contractData="contractData"
					:processInstanceId="props.contract?.processInstanceId"
					:status="props.status"
					:isApproval="props.contract?.isApproval" />

				<!-- 合同信息 -->
				<contract-information
					v-if="activeKey == 'contract'"
					:contractData="contractData"
					:status="props.status"
					:approvalStatus="contractData.approvalStatus"
					:enterpriseData="enterpriseData"
					:processInstanceId="props.contract?.processInstanceId"
					:enterPriseUserId="enterPriseUserId"
					@close="close"></contract-information>

				<!-- 房间信息 -->
				<room-information
					v-if="activeKey == 'room'"
					:id="props.id || props.contract?.businessId"
					:approvalStatus="contractData.approvalStatus"
					:staffInfo="staffInfo"
					:status="props.status"
					:contractLabel="contractLabel"
					:processInstanceId="props.contract?.processInstanceId"></room-information>

				<!-- 房间合同 -->
				<tenant
					v-if="activeKey == 'single'"
					:enterPriseApprovalStatus="contractData.approvalStatus"
					:enterPriseContractId="props.id || props.contract?.businessId"
					:type="contractData.type"
					:query="{}"
					:tabActiveKey="tabActiveKey"
					:enterpriseName="contractData.enterPriseDTO?.enterPriseName"
					class="room-contract"
					:isShow="true"></tenant>

				<!-- 入住信息 -->
				<check-in-information
					:approvalStatus="contractData.approvalStatus"
					v-if="activeKey === 'checkIn'"
					:data="contractData"
					@close="close"></check-in-information>

				<!-- 账单信息 -->
				<bill-information
					:approvalStatus="contractData.approvalStatus"
					:type="contractData.signType === 5 ? 2 : 1"
					v-if="activeKey == 'bill'"
					:contractType="2"
					:id="props.id || props.contract?.businessId" />

				<!-- 开具发票 -->
				<invoiceing
					v-if="activeKey == 'invoiceing'"
					:data-source="contractData"
					:enter-type="2"
					:id="contractData.id || []"
					:data-dept="{deptId: contractData.signDeptId, deptName: contractData.signDepName}"
					@bill="close" />
				<follow-record-dialog :contract-id="contractData.id" v-if="activeKey == 'follow'" />
			</a-col>
			<a-col
				:span="
					props.contract?.isApproval && ['singleRentOut', 'contract', 'room', 'single', 'checkIn', 'bill'].includes(activeKey)
						? 7
						: 0
				"
				class="approval-process-list-right">
				<!--  class="approval-process-list-right" -->
				<approval :status="props.status" :processInstanceId="props.contract?.processInstanceId"></approval>
			</a-col>
		</a-row>
		<!-- 新增 补签审批展示 -->

		<template #footer>
			<template v-if="!props.hideButton">
				<a-button
					v-if="
						[23, 24, 25, 26].includes(contractData.label) &&
						['3', '-1'].includes(props.approvalStatus as string) &&
						hasPermissions(['mk_contract_charter_party_zf'])
					"
					@click="openCancel()">
					作废
				</a-button>
				<!-- 企业新签 续签 补签允许作废 -->
				<a-button
					v-if="
						['2', '4'].includes(props.approvalStatus as string) &&
						hasPermissions(['mk_contract_charter_party_zf']) &&
						(contractData.signType === 1 || contractData.signType === 2)
					"
					@click="openCancel()">
					作废
				</a-button>
				<a-button
					v-if="showBtn('supplementary') && hasPermissions(['mk_contract_charter_party_bq']) && contractData.signType !== 5"
					@click="supplementaryF">
					补签
				</a-button>
				<a-button v-if="showBtn() && hasPermissions(['mk_contract_charter_party_tz'])" @click="rentingOut(1)">退租</a-button>
				<a-button
					v-if="[34].includes(contractData.label) && showBtn() && hasPermissions(['mk_contract_charter_party_tz'])"
					@click="rentingOut(2)">
					结算
				</a-button>
				<a-button v-if="showBtn() && hasPermissions(['mk_contract_charter_party_xz'])" type="primary" @click="reletF">
					续租
				</a-button>
				<a-button
					v-if="['2', '4'].includes(props.approvalStatus as string) && hasPermissions(['mk_contract_charter_party_tjbzht'])"
					@click="resubmitF">
					重新提交
				</a-button>
			</template>

			<div v-if="props.contract?.isApproval && isShowPrior" style="display: inline-block; margin-left: 8px">
				<!-- 非前合同 -->
				<!-- 企业合同暂时只处理续租前合同 -->
				<div
					v-if="
						!isPriorContract &&
						![31, 32].includes(contractData.label) &&
						[2].includes(contractData.signType) &&
						activeKey === 'contract'
					">
					<a-button type="primary" :loading="loading" :disabled="loading" @click="checkParents()">
						{{ signTypeList[contractData.signType] + '前合同' }}
					</a-button>
				</div>
				<!-- 前合同 -->
				<div v-else-if="isPriorContract && activeKey === 'contract'">
					<a-button type="primary" :loading="loading" :disabled="loading" @click="contractDetails(false)">
						{{ signTypeList[contractData.signType] + '后合同' }}
					</a-button>
				</div>
			</div>
		</template>
	</a-modal>
	<!-- 作废 -->
	<contracts-cancel v-model:visible="isShow.contractsCancel" :info="info" @success="options.onCancel" />

	<!-- 批量退租 -->
	<batch-retreat-rent
		:isShow="false"
		:enter-prise-contract-id="props.id"
		:resubmitId="isShow.resubmitId"
		v-model:visible="visibles.showRetreatRent"
		:rentingOutType="rentingOutType"
		@success="close" />

	<!-- 退租确认 -->
	<retreat-rent-pre v-model:visible="visibles.showRetreatRentPre" :enterPriseContractId="props.id" :isShow="false" @success="close" />

	<!-- 续租 -->
	<signing-dialog
		v-model:visible="visibles.addCharter"
		:reletId="isShow.reletId"
		:signing-type="'charter'"
		:resubmitId="isShow.resubmitId as string"
		:approvalStatus="props.approvalStatus as string"
		:supplementaryId="isShow.supplementaryId"
		@success="close" />

	<!-- 包租合同批量 退 作废  查看续租父合同-->
	<batch-operate
		v-model:visible="visibles.batchOperate"
		:hideDetails="true"
		:type="batchOperateTupe"
		:id="params.contractPid"
		:currentSign="params.signTypeList[0]"
		:contract="contract"
		@success="
			() => {
				isShowBtn()
				contractDetails()
			}
		" />

	<!-- 企业合同子合同续租 -->
	<child-renewal
		v-model:visible="visibles.shoowRenewal"
		:id="contractData.id as string"
		:enterContractEndDate="contractData.endTime"
		:isApproval="props.contract?.isApproval"
		:cooperation-end-date="cooperationEndDate"
		@success="contractDetails" />

	<!-- 补签协议 -->
	<!-- <supplementary-agreement v-model:visible="visibles.supplementaryAgreement"></supplementary-agreement> -->
</template>

<script setup lang="ts">
	import {createVNode, onMounted, reactive, ref, toRef, watch} from 'vue'
	import ContractInformation from './contract-information.vue'
	import {QuestionCircleOutlined} from '@ant-design/icons-vue'
	import RoomInformation from './room-information.vue'
	import Tenant from '@/pages/contract/tenant/index.vue'
	import CheckInInformation from './check-in-information.vue'
	import BillInformation from './bill-information.vue'
	import {
		getEnterContractDetails,
		getList,
		hasApproval,
		isCheckInFun,
		contractResetValid,
		getBeforeRenewalList,
		getRenewalContractNum
	} from '@/api/charter-contract'
	import ContractsCancel from '@/components/contract/enterprise-customer-management/contracts-cancel.vue'
	import SingleRoomRentOutDetails from '@/components/contract/contract-detail-dialog/charter-contract/single-room-rent-out-details.vue'
	import SigningDialog from '@/components/contract/signing/signing-dialog.vue'
	import {useStore} from '@/store'
	import approval from '@/components/contract/contract-detail-dialog/charter-contract/approve.vue'
	import invoiceing from '@/components/contract/contract-detail-dialog/invoiceing.vue'
	import {enterpriseDetails} from '@/api/enterprise-library'
	import {message, Modal} from 'ant-design-vue'
	import dayjs from 'dayjs'
	import {getEnterPriseInfo, getInvoicingPrice} from '@/api/contract'
	import BatchOperate from '@/components/contract/contract-detail-dialog/charter-contract/batch-operate.vue'
	import childRenewal from '@/components/contract/contract-detail-dialog/charter-contract/child-renewal.vue'
	import BatchRetreatRent from '@/components/contract/contract-detail-dialog/charter-contract/batch-retreat-rent.vue'

	const hasPermissions = useStore().hasPermissions
	const emits = defineEmits(['update:visible', 'close'])

	const props = withDefaults(
		defineProps<{
			visible: boolean
			id?: string
			status?: any
			// 是否显示按钮
			operationVisible?: boolean
			data?: any
			contract?: {
				businessId?: string
				// 判断是否来源于主应用
				source?: string
				// 判断是否是审批
				isApproval?: boolean
				// 审批模块类型
				approvalType?: string
				// 审批模块
				processInstanceId?: string
				isShow?: boolean
			}
			approvalStatus?: string | number
			hideButton?: boolean
			// 跳转开具发票
			activeKeyProps?: string
			isShowPrior?: boolean
		}>(),
		{
			isShowPrior: true
		}
	)

	const tabActiveKey = ref<string>('')

	const detailTabs = ref([
		{
			key: 'contract',
			value: '合约信息'
		},
		{
			key: 'room',
			value: '房间信息'
		},
		{
			key: 'single',
			value: '房间合同'
		},
		{
			key: 'checkIn',
			value: '入住信息'
		},
		{
			key: 'bill',
			value: '账单信息'
		},
		{
			key: 'invoiceing',
			value: '开具发票'
		}
	])

	const signTypeList: {
		[key: string | number]: any
	} = {1: '新签', 2: '续签', 3: '转租', 4: '换房', 5: '补签'}

	const info = reactive({
		id: props.id,
		name: null
	})

	const visibles = reactive<any>({
		wirteOffBusiness: false,
		search: false,
		addCharter: false,
		teleport: false,
		showDetails: false,
		showRetreatRent: false,
		showRetreatRentPre: false,
		contractsCancel: false,
		increase: false,
		batchOperate: false,
		follow: false,
		shoowRenewal: false
	})

	const isShow = reactive<any>({
		contractsCancel: false,
		resubmitId: props.id,
		reletId: props.id,
		supplementaryId: null
	})
	// 企业合同状态
	const contractLabel = ref(null)

	const resetId = ref<any>(null)

	const activeKey = ref<string>('')

	const isShowFooter = ref<any>(undefined)

	const contractData = ref<any>([])

	const staffInfo = ref<any>({})

	const isCheckIn = ref(false)

	const options = reactive({
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
		}
	})

	const batchOperateTupe = ref<any>(1)

	const rentingOutType = ref('')

	watch(
		() => activeKey.value,
		newVal => {
			showBtn()
			if (newVal === 'contract' || newVal === 'bill') {
				isShowFooter.value = undefined
			} else {
				isShowFooter.value = null
			}
		}
	)

	// const enterpriseList = ref<any>([])
	const enterpriseData = ref<any>([])

	const isShowBtn = () => {
		if (activeKey.value === 'contract' || activeKey.value === 'bill') {
			if (props.status === 32) {
				return false
			} else if (props.status === 31) {
				return false
			} else if (props.status === 41) {
				return false
			}
			return true
		} else {
			return false
		}
	}

	const enterPriseUserId = ref('')
	const isPriorContract = ref(false)
	const loading = ref(false)
	const cooperationEndDate = ref('')
	const contractDetails = async (before = false) => {
		loading.value = true
		let id = before ? contractData.value.contractPid : (props.id as string) || (props.contract?.businessId as string)
		await getEnterContractDetails(id).then((res: any) => {
			loading.value = false
			isPriorContract.value = before

			contractData.value = res.data
			tabActiveKey.value = ''
			contractLabel.value = res.data.label
			if ([31, 32, 34, 33].includes(res.data.label)) {
				tabActiveKey.value = '3'
			}
			params.signTypeList = [res.data.signType, 5]
			// 加上 合同类型和id 为了开具发票的判断
			contractData.value.contractType = 2
			contractData.value.enterType = 2
			staffInfo.value = res.data.enterPriseDTO
			info.name = res.data.enterPriseDTO.enterPriseName
			info.id = props.id
			cooperationEndDate.value = res.data.enterPriseDTO.endTime
			enterPriseUserId.value = res.data.enterPriseUserId
			enterpriseDetails(res.data?.enterPriseDTO.id).then((res: any) => {
				enterpriseData.value = res.data.contacts?.map((o: any) => {
					return {
						...o,
						period: o.linkmanName + '/' + o.linkmanPhone + `${o.linkmanPost ? '/' + o.linkmanPost : ''}`
					}
				})
			})
			hasCheckIn(props.id as string)

			if (props.activeKeyProps) {
				activeKey.value = props.activeKeyProps
			}
		})
	}

	watch(
		() => props.visible,
		async newVal => {
			if (newVal) {
				if (!props.contract?.isApproval) {
					activeKey.value = 'contract'
					isShowBtn()
					contractDetails()
				}

				if (props.contract?.approvalType) {
					isShowBtn()
					await contractDetails()
					if (props.contract?.source === 'singleRentOut') {
						detailTabs.value.unshift({
							key: 'singleRentOut',
							value: '退租信息'
						})
					}
					isPriorContract.value = props.isPriorContract
					// if (isPriorContract.value) {
					// 	await contractDetails(isPriorContract.value)
					// }
					activeKey.value = props.contract?.source as string
				}
			}
		}
	)

	const close = () => {
		emits('update:visible', false)
		setTimeout(() => emits('close'), 100)
	}

	onMounted(async () => {})

	//重新提交
	const resubmitF = async (data: any) => {
		isShow.resubmitId = props.id
		isShow.reletId = ''
		isShow.supplementaryId = null
		if ([23, 24, 25, 26].includes(contractData.value.label)) {
			if (contractData.value.signType === 2) {
				reletF()
			}

			// 补签重新提交
			if (contractData.value.signType === 5) {
				supplementaryF()
			}

			visibles.addCharter = true
		} else if (contractData.value.label === 31 || contractData.value.label === 32) {
			// visibles.showRetreatRent = true
			rentingOut()
		}
	}

	/** 重置 */
	const reset = async (data: any) => {
		if (await checkChildContract(contractData.value)) return
		if (await checkCharter(contractData.value)) return
		if (await checkChild(contractData.value, 7)) return

		contractResetValid(props.id as string, {isExcludeEnergy: true}).then(({data}) => {
			if (data) {
				resetId.value = props.id
				isShow.resubmitId = null
				isShow.reletId = null
				isShow.supplementaryId = null
				visibles.addCharter = true
			} else {
				message.error('已产生收支无法重置')
			}
		})
	}

	/** 补签 */
	const supplementaryF = async () => {
		// if (await checkChildContract(contractData.value)) return
		if (await checkCharter(contractData.value)) return

		if (!contractData.value.enterPriseDTO.endTime) return message.warning('已与该企业终止合约,无法操作补签')
		isShow.resubmitId = ''
		isShow.reletId = ''
		isShow.supplementaryId = props.id
		visibles.addCharter = true
	}

	const showBtn = (type = 'default') => {
		let labelArr = [23, 24, 25, 26]

		// 补签限制
		if (type === 'supplementary') {
			labelArr = [23, 24, 25]
		}

		let temp = false
		if (
			!props.contract?.isApproval &&
			['3', '-1'].includes(props.approvalStatus as string) &&
			labelArr.includes(contractData.value.label)
		) {
			temp = true
		}

		return temp
	}

	// 续租
	const reletF = async () => {
		if (await checkChildContract(contractData.value)) return
		if (await checkCharter(contractData.value)) return
		// if (await batch(contractData.value, 2)) return

		if (!contractData.value.enterPriseDTO.endTime) return message.warning('已与该企业终止合约,无法操作续租')
		if (dayjs(contractData.value.enterPriseDTO.endTime).diff(contractData.value?.endTime, 'day') == 0)
			return message.warning('无法续租,当前合同周期结束日期等于合作周期结束日期,如需续租,请先至【企业库】延长与承租企业合作周期')

		isShow.reletId = props.id
		isShow.resubmitId = ''
		isShow.supplementaryId = null
		visibles.shoowRenewal = true
	}

	// 退租
	const rentingOut = async (type = 1) => {
		if (await checkChildContract(contractData.value)) return
		if (await checkInvoicingPrice(contractData.value)) return
		if (await batch(contractData.value, 1)) return

		isShow.resubmitId = ''
		rentingOutType.value = ''

		if (isCheckIn.value) {
			prompt(1, type)
			return
		}

		openRetreatRent(type)
	}

	const openRetreatRent = type => {
		if (type === 0) visibles.showRetreatRent = true
		if (type === 1) visibles.showRetreatRentPre = true
		if (type === 2) {
			rentingOutType.value = 'settlement'
			visibles.showRetreatRent = true
		}
	}

	/** 作废 */
	const openCancel = async () => {
		if (await checkChildContract(contractData.value)) return
		if (await checkInvoicingPrice(contractData.value)) return
		if (await checkChild(contractData.value, 3)) return
		if (await batch(contractData.value, 3)) return

		if (isCheckIn.value) {
			prompt(1)
			return
		}
		isShow.contractsCancel = true
	}

	/** 检查企业终止 */
	const checkCharter = async (row: any) => {
		const res = await getEnterPriseInfo({
			enterPriseId: row.enterPriseId
		})
		if (res.data?.isBreak === 2) {
			message.warning('已与该企业终止合约,无法操作')
			return true
		}
		return false
	}

	/** 检查子合同 */
	const checkChildContract = async (row: any) => {
		const res = await hasApproval(row.id)
		console.log('🚀 ~ file: index.vue:473 ~ handlerClick ~ res:', res)
		if (res.data) {
			message.warning('企业子合同正在审批流（审批中、审批驳回、审批撤销）中，请先完成企业子合同审批')
			return res.data
		}
		return false
	}

	/** 应收款账单已开发票未冲红情况检验 退 作废 */
	const checkInvoicingPrice = async (row: any) => {
		const res = await getInvoicingPrice({enterContractId: row.id})
		if (Number(res.data) > 0) {
			message.warning('操作失败！存在未收款但已开具发票的账单明细，请先作废发票申请或冲红该发票，再操作')
			return true
		}
		return false
	}

	/** 作废 重置 检验子合同是否有续租 */
	const checkChild = async (row: any, type: any) => {
		let tips = '作废失败，该企业合同存在部分子合同已续租。如需作废该合同，请先作废关联的续租后子合同!'
		if (type === 7) tips = '重置失败，该企业合同存在部分子合同已续租.如需重置该合同，请先作废关联的续租后子合同!'

		const res = await getRenewalContractNum(row.id)
		if (Number(res.data) > 0) {
			message.warning(tips)
			return true
		}
		return false
	}

	const params = reactive<any>({
		contractStatus: 2,
		signTypeList: [],
		approvalStatusList: [-1, 3],
		contractPid: '',
		transitionType: 0
	})
	const batch = async (row: any, type: any) => {
		// 企业合同批量操作 续租 退租 作废
		params.contractPid = row.id

		let res: any = []
		if (type !== 2) {
			res = await getList(params)
		}

		// 审批页面下的 批量操作续租其实是查看父合同
		if (props.contract?.isApproval && type === 2) {
			res = await getBeforeRenewalList(row.id)
		}

		// 存在多条关联才进入批量操作
		if (res.data.length > 1) {
			batchOperateTupe.value = type
			visibles.batchOperate = true
			return true
		}

		return false
	}

	const prompt = (action: number, type = 1) => {
		Modal.confirm({
			width: 470,
			title: '提示',
			content: () =>
				createVNode('div', {}, [
					createVNode('div', {
						innerHTML: `当前包租合同还有入住人,继续${action === 1 ? '退租' : '作废'}将同步操作员工搬离,请确定是否继续${
							action === 1 ? '退租' : '作废'
						}`
					})
				]),
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			okText: '确定',
			cancelText: '取消',
			async onOk() {
				// 判断是退租还是作废
				if (action === 1) {
					// 退租
					openRetreatRent(type)
				} else {
					// 作废
					isShow.contractsCancel = true
				}
			}
		})
	}

	// 判断是否有人入住
	const hasCheckIn = (id: string) => {
		if (!id) return
		isCheckInFun(id).then((res: any) => {
			isCheckIn.value = res.data
		})
	}

	/** 查询是否有多个企业父合同 */
	const checkParents = async () => {
		if (await batch(contractData.value, 2)) return

		// 如果只有一条
		contractDetails(true)
	}
</script>

<style lang="less">
	.charter-contract-dialog {
		.ant-modal-body {
			padding: 0;
			height: 90vh;
			overflow: auto;
		}
	}

	.approval-process-list-right {
		min-height: 100%;
		padding-left: 15px;
	}
</style>
